package 尚硅谷juc大厂.test23;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class Test23 {

    static ReentrantReadWriteLock readWriteLock=new ReentrantReadWriteLock();
    static ReentrantReadWriteLock.ReadLock readLock = readWriteLock.readLock();
    static ReentrantReadWriteLock.WriteLock writeLock = readWriteLock.writeLock();
    private static volatile int num=0;
    public static void main(String[] args) {

        /**
         * 为了能够保证数据一致性，和保证数据不丢失，那么就可以使用锁降级原则
         * 主要依靠2点：
         *      1:读写是不能并发执行的
         *      2:写锁可以降级为读锁
         *
         */
        new Thread(()->{
            writeLock.lock();//先上写锁
            num=10;
            readLock.lock();//在释放写锁之前先把读锁上好
            writeLock.unlock();//然后再释放写锁
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("t1线程  当前得num值为："+num);
            readLock.unlock();//释放读锁
        },"t1").start();

        new Thread(()->{
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            writeLock.lock();//先上写锁
            num=20;
            readLock.lock();//在释放写锁之前先把读锁上好
            writeLock.unlock();//然后再释放写锁
            System.out.println("t2线程  当前得num值为："+num);
            readLock.unlock();//释放读锁
        },"t2").start();

    }
}


